﻿// Define the entry point
$(document).ready(function () {
    // The DOM (document object model) is constructed
    // We will initialize and run our plugin here
    ExecuteOrDelayUntilScriptLoaded(DocumentReadyDelegate, "sp.js");
});

this.DocumentReadyDelegate = function () {
    IcoToThumbs();
//    MakeTable();
    imagePreview();
}

this.MakeTable = function () {
    var result = $('#CSR.srch-WPBody .srch-results');
    var tbl = $('<table></table>');

    var icon = $('.srch-Icon');
    icon.each(
        function (index) {
            $(this).css('float', 'right');
            var srchTitle2 = $(this).nextAll('.srch-Title2:first');
            var srchDesc2 = $(this).nextAll('.srch-Description2:first');
            var srchMeta2 = $(this).nextAll('.srch-Metadata2:first');
            var srchMeta1 = $(this).nextAll('.srch-Metadata1:first');
            var row = $('<tr/>');
            tbl.append(row);
            var cell1 = $('<td valign=\'top\' width=\'1px\' align=\'Right\'/>');
            row.append(cell1);
            cell1.append(this);
            var cell2 = $('<td/>');
            row.append(cell2);
            cell2.append(srchTitle2);
            cell2.append(srchDesc2);
            cell2.append(srchMeta2);
            cell2.append(srchMeta1);
        });
    result.prepend(tbl);
}

this.IcoToThumbs = function () {
    var ctx = new SP.ClientContext.get_current();
    var webUrl = ctx.get_url();
    if (webUrl != "/")
        webUrl += "/";

    var desc2 = $('.srch-Description2');
    desc2.each(
        function (index) {
            var node = $('<div></div>').insertBefore($(this));
            var imgNode = node.append('<div style="float: left; margin-left: 24px;"><a class="preview"><img class="preview" style="border-style:none;width:0px" src=""></a></div>');
            var container = node.append('<div class="srch-Info"></div>');
            container.append(node.next());
            container.append(node.next());
            container.append(node.next());
            container.append('<div style="clear:both"></div>');

            var url = $(this).nextAll('.srch-Metadata1:first').children('span:first').children('.srch-URL2').text();

            var objUrl = parseUri(url);
            var hostAddress = objUrl["protocol"] + "://" + objUrl["authority"];

            if (url.match(/^.+\.((doc)|(docx)|(ppt)|(pptx)|(xps)|(aspx)|(pdf)|(xlsx)|(dwg)|(wmv)|(zip))(\?+.*)?$/) != null) {
                var aNode = $('a.preview', imgNode);
                aNode.attr('rel', webUrl + '_layouts/SPThumbnailExtender/MobileGenericHandler.ashx?usecache=true&doc=' + encodeURIComponent(url));
                if (url.match(/^.+\.((pptx)|(docx)|(ppt))$/) != null) {
                    aNode.attr('href', "javascript:OpenDialog('" + hostAddress + "/_layouts/SPThumbnailExtender/ThumbSilverlight.aspx?doc=" + url.replace("'", "\\'") + "')");
                }

                var width = 66;
                var height = 86;
                var hUrl;
                hUrl = webUrl + '_layouts/SPThumbnailExtender/MobileGenericHandler.ashx?usecache=true&doc=' + encodeURIComponent(url);
                if (url.match(/^.+\.((pptx)|(ppt)|(html)|(aspx))(\?+.*)?$/) != null) {
                    width = 100;
                    height = 75;
                }
                hUrl = hUrl + "&w=" + width + "&h=" + height;

                var img = $('img.preview', imgNode);
                img.attr('src', hUrl).load(function () {
                    var img = $(this);
                    img.css({ 'margin-right': '10px', 'border': 'solid 1px #ccc' })
                    img.animate({ width: width + "px" }, 400);
                });
            }
        }
    )
};

this.imagePreview = function () {
    /* CONFIG */

    yOffset = 100;
    xOffset = 30;
    yScreen = screen.height;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result

    /* END CONFIG */
    $("a.preview").hover(function (e) {
        this.t = this.title;
        var c = (this.t != "") ? "<br/>" + this.t : "";
        $("body").append("<p id='preview'><img src=\"" + this.rel + "\" alt='Image preview' />" + c + "</p>");
        $("#preview")
                        .css("top", (e.pageY - yOffset) + "px")
                        .css("left", (e.pageX + xOffset) + "px")
                        .fadeIn("fast");
    },
        function () {
            this.title = this.t;
            $("#preview").remove();
        });
        $("a.preview").mousemove(function (e) {
            var y = (e.pageY - yOffset);
        $("#preview")
                        .css("top", y + "px")
                        .css("left", (e.pageX + xOffset) + "px");
    });
};

this.OpenDialog = function (docurl) {
    var options = {
        url: docurl,
        width: 800,
        height: 600,
        showMaximize: true

    };
    SP.UI.ModalDialog.showModalDialog(options);
};


this.parseUri = function parseUri(sourceUri) {
    var uriPartNames = ["source", "protocol", "authority", "domain", "port", "path", "directoryPath", "fileName", "query", "anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    for (var i = 0; i < 10; i++) {
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    if (uri.directoryPath.length > 0) {
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    return uri;
}